package caronas.util;

import br.com.caelum.vraptor.ioc.Component;
import caronas.modelo.Service;
import caronas.modelo.Usuario;

import com.restfb.DefaultFacebookClient;
import com.restfb.FacebookClient;
import com.restfb.Parameter;
import com.restfb.FacebookClient.AccessToken;
import com.restfb.types.FacebookType;
import com.restfb.types.User;

@Component
public class FacebookUtils {
	private static String MY_APP_ID = "154827474661020";
    private static String MY_APP_SECRET = "d5ef9de9588193412f9f659e6c7a34dd";
	
	public Service montarService(String uid, String token){
		FacebookClient facebookClient = new DefaultFacebookClient(token);
		User user = facebookClient.fetchObject("me", User.class);
		boolean gender = user.getGender() == "male"? true : false;
		String location = ( user.getLocation() != null ) ? user.getLocation().getName() : null;                                                                
		Service service = new Service("facebook", uid, user.getName(), user.getEmail(), token, gender, location, user.getUsername());
		return service;
		

	}
	
	public Usuario montarUsuario(Service service){
		Usuario usuario = new Usuario(service);
		service.setUsuario(usuario);
		return usuario;
	}
	
	public boolean enviarMensagem(Service origemService, Service destinoService, String mensagem){
		AccessToken accessToken = new DefaultFacebookClient().obtainAppAccessToken(MY_APP_ID, MY_APP_SECRET);
		FacebookClient facebookClient = new DefaultFacebookClient(accessToken.getAccessToken());
		FacebookType publishMessageResponse =facebookClient.publish(destinoService.getUid()+"/notifications", FacebookType.class,
                Parameter.with("template",mensagem));

		//FacebookType publishMessageResponse = facebookClient.publish(idDestinatario+"/feed", FacebookType.class, Parameter.with("message", mensagem));
		
		if(publishMessageResponse != null){
			return true;
		}
		return false;
	}
}
